package com.atguigu.yygh.order.service.impl;

import com.atguigu.yygh.enums.PaymentTypeEnum;
import com.atguigu.yygh.model.order.OrderInfo;
import com.atguigu.yygh.order.service.OrderService;
import com.atguigu.yygh.order.service.PaymentService;
import com.atguigu.yygh.order.service.WeixinService;
import com.atguigu.yygh.order.utils.ConstantPropertiesUtils;

import com.atguigu.yygh.order.utils.HttpClient;
import com.github.wxpay.sdk.WXPayUtil;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;


import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


/**
 * @description: TODO
 * @author: 化一帆
 * @date: 2022/12/9 20:37
 * @version: v1.0
 */
@Service
public class WeixinServiceImpl implements WeixinService {

    @Autowired
    private OrderService orderService;

    @Autowired
    private PaymentService paymentService;

    @Autowired
    RedisTemplate redisTemplate;
    @Override
    public Map createNative(Long orderId) {

        //1.先看redis中是否有支付链接
        //1、检查redis中是否存在该订单的支付链接
        Map map = (Map) redisTemplate.boundValueOps(orderId.toString()).get();
        if(map!=null){
            return map;
        }


        //2.为订单创建支付记录【向支付记录表中添加数据】
        //根据订单id，查询订单的信息
        OrderInfo order = orderService.getById(orderId);
        paymentService.createPayment(order, PaymentTypeEnum.WEIXIN.getStatus());




        try {
            //3.调用微信端的“统一下单接口”，获取codeurl
            //设置参数，调用微信生成二维码接口
            //把参数转换成xml格式，使用商户key进行加密
            //3、保存交易记录（一个订单只能一条交易记录）
            paymentService.createPayment(order, PaymentTypeEnum.WEIXIN.getStatus());

            //4、调用微信统一下单接口--封装参数
            Map paramMap=new HashMap();
            paramMap.put("appid", ConstantPropertiesUtils.APPID);//公众账号ID
            paramMap.put("mch_id", ConstantPropertiesUtils.PARTNER);//商户号
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());//随机字符串	32位以内
            Date reserveDate = order.getReserveDate();//安排日期
            String reserveDateString = new DateTime(reserveDate).toString("yyyy/MM/dd");
            String body = reserveDateString + "就诊"+ order.getDepname();
            paramMap.put("body", body);//描述：2022/07/17 就诊 多发性硬化专科门诊
            paramMap.put("out_trade_no", order.getOutTradeNo());
            //paramMap.put("total_fee", order.getAmount().multiply(new BigDecimal("100")).longValue()+"");
            paramMap.put("total_fee", "1");//订单总金额，测试1分钱
            paramMap.put("spbill_create_ip", "127.0.0.1");
            paramMap.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify");//没有
            paramMap.put("trade_type", "NATIVE");


            //5.调用微信生成二维码的接口，使用httpClient进行调用
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            //设置map参数【先将map转换成xml格式，再将xml进行加密】
            client.setXmlParam(WXPayUtil.generateSignedXml(paramMap, ConstantPropertiesUtils.PARTNERKEY));
            client.setHttps(true);//设置支持https请求
            client.post();//完成发送


            //6.微信接口返回相关的数据
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);//将xml格式转换成map格式

            ///7、封装结果
            Map returnmap = new HashMap<>();

            returnmap.put("orderId", orderId);//订单id
            returnmap.put("totalFee", order.getAmount());//订单金额
            returnmap.put("resultCode", resultMap.get("result_code"));//SUCCESS、FAIL
            returnmap.put("codeUrl", resultMap.get("code_url"));//二维码支付链接

            //8、将结果暂存到redis五分钟(key,value,存储的时间)
            redisTemplate.opsForValue().set(orderId.toString(),returnmap, 5, TimeUnit.SECONDS);

            return returnmap;
        } catch (Exception e) {
            e.printStackTrace();
        }

       return null;
}

    /**
     * @description: 查询订单的支付状态
     * @author 化一帆
     * @date 2022/12/11 13:32
     */
    @Override
    public Map queryPayStatus(Long orderId) {
        //1、查询平台端的订单，getOutTradeNo 调用微信端查询支付状态时使用
        OrderInfo orderInfo = orderService.getById(orderId);

        //2、调用微信端的  查询支付状态接口
        //2.1 url接口地址
        String url = "https://api.mch.weixin.qq.com/pay/orderquery";

        //2.2 参数封装
        Map<String,String> paramMap = new HashMap<>();
        paramMap.put("appid",ConstantPropertiesUtils.APPID);
        paramMap.put("mch_id",ConstantPropertiesUtils.PARTNER);
        paramMap.put("out_trade_no",orderInfo.getOutTradeNo());
        paramMap.put("nonce_str",WXPayUtil.generateNonceStr());

        try {
            //2.3 map格式转成xml格式
            String xmlParam = WXPayUtil.generateSignedXml(paramMap, ConstantPropertiesUtils.PARTNERKEY);
            //2.4 发请求
            HttpClient httpClient = new HttpClient(url);
            httpClient.setXmlParam(xmlParam);
            httpClient.setHttps(true);
            httpClient.post();

            //2.5 获取微信的返回值（xml格式的字符串），转成map
            String xmlResponse = httpClient.getContent();//返回值
            Map<String, String> responseMap = WXPayUtil.xmlToMap(xmlResponse);

            return responseMap;//接口调用成功（不意味着支付成功）

        } catch (Exception e) {
            e.printStackTrace();
            return null;// 接口调用失败
        }

    }
}